package com.lzx.iteam;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.lzx.iteam.bean.CloudGroup;
import com.lzx.iteam.net.AddContactListMsg;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.util.*;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static io.rong.imlib.statistics.UserData.email;
import static io.rong.imlib.statistics.UserData.phone;

/**
 * Created by Megan on 15/8/14.
 * 手工添加
 */
public class AddContactByHandActivity extends Activity implements View.OnClickListener {


    private RelativeLayout mEtImageLayout,mRlSexLayout;
    private EditText mEtName, mEtCompany,  mEtPosition, mEtPhone1,
    //            mEtDepartment,mEtPhone2,//电话号码改为只有一个，第二个号码暂时隐藏
    mEtEmail, mEtAddress, mEtMessage;
    private LinearLayout mLlBack;
    private LinearLayout mMainView;
    private TextView mTvSave,mSex,mPhoneNote;
    private String mGroupId, mTagId, mGroupName;
    private String mContactSex = "0";
    private View mImageLine,mSexLine,mCompanyLine;

    private CloudGroup mCloudGroup = null;
    private PopupWindow mSetSexPop;

    private final int MSG_ADD_CONTACT = 1000;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_ADD_CONTACT:
                    Intent toCreate = new Intent(AddContactByHandActivity.this, CreateGroupActivity.class);
                    toCreate.putExtra(CloudGroup.class.getName(), mCloudGroup);
                    toCreate.putExtra("code", msg.arg1);
                    toCreate.putExtra(Constants.INTENT_TAG_ID, mTagId);
                    toCreate.putExtra("contact_count", "1");
                    if (msg.arg1 == 0) {
                        if (msg.obj != null) {
                            if( ((HashMap<String,String>)msg.obj).get("success_num")!=null) {
                                toCreate.putExtra("err_num", ((HashMap<String, String>) msg.obj).get("err_num"));
                                toCreate.putExtra("success_num", ((HashMap<String, String>) msg.obj).get("success_num"));
                                toCreate.putExtra("err_contact_names", ((HashMap<String, String>) msg.obj).get("err_contact_names"));
                            }else{
                                toCreate.putExtra("err_num", "0");
                                toCreate.putExtra("success_num", "1");
                                toCreate.putExtra("err_contact_names", "");
                            }
                        }

                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(AddContactByHandActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            finish();
                            Toast.makeText(AddContactByHandActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                        }
                    }
                    toCreate.putExtra("where", "addContact");
                    startActivity(toCreate);
                    finish();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_contact_by_hand);
        initView();
        initIntentData();
    }
    private void initView() {
        mEtImageLayout=(RelativeLayout)findViewById(R.id.edit_rl_image);
        mImageLine=(View)findViewById(R.id.v_image_line);
        mSexLine=(View)findViewById(R.id.v_sex_line);
        mCompanyLine=(View)findViewById(R.id.v_company_line);
        mImageLine.setVisibility(View.GONE);
        mMainView = (LinearLayout) findViewById(R.id.add_contact_by_hand_main);
        mEtName = (EditText) findViewById(R.id.cloud_contact_name);
        mSex = (TextView) findViewById(R.id.edit_tv_sex);
        mEtPosition = (EditText) findViewById(R.id.cloud_contact_position);
//        mEtDepartment = (EditText) findViewById(R.id.add_contact_department);
        mEtPhone1 = (EditText) findViewById(R.id.cloud_contact_phone);
//        mEtPhone2 = (EditText) findViewById(R.id.add_contact_phone2);
        mEtCompany = (EditText) findViewById(R.id.cloud_contact_company);
        mEtEmail = (EditText) findViewById(R.id.cloud_contact_email);
        mEtAddress = (EditText) findViewById(R.id.cloud_contact_address);
        mEtMessage = (EditText) findViewById(R.id.cloud_contact_note);
        mLlBack = (LinearLayout) findViewById(R.id.add_contact_back);
        mTvSave = (TextView) findViewById(R.id.add_contact_ok);
        mPhoneNote=(TextView)findViewById(R.id.edit_tv_phone_note);
        mRlSexLayout = (RelativeLayout) findViewById(R.id.edit_rl_sex);
        mRlSexLayout.setOnClickListener(this);
        mTvSave.setOnClickListener(this);
        mLlBack.setOnClickListener(this);
        mEtImageLayout.setVisibility(View.GONE);
        mRlSexLayout.setVisibility(View.GONE);
        mPhoneNote.setVisibility(View.GONE);
        mSexLine.setVisibility(View.GONE);
        mCompanyLine.setVisibility(View.GONE);
    }

    private void initIntentData() {
        Intent intent = getIntent();
        mGroupId = intent.getStringExtra("group_id");
        mTagId = intent.getStringExtra("tag_id");
        mCloudGroup = (CloudGroup) intent.getSerializableExtra(CloudGroup.class.getName());
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.add_contact_back:
                finish();
                break;
            case R.id.add_contact_ok:
                if (StringUtil.isEmpty(mEtPhone1.getText().toString().trim())) {
                    Toast.makeText(this, "电话号码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(StringUtil.isEmpty(mEtName.getText().toString().trim())){
                    Toast.makeText(this, "姓名不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!StringUtil.isMobile(mEtPhone1.getText().toString().trim())) {
                    Toast.makeText(this, "手机号码不正确", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!StringUtil.isEmpty(mEtEmail.getText().toString().trim()) && !StringUtil.checkEmail(mEtEmail.getText().toString().trim())) {
                    Toast.makeText(this, "邮箱格式不正确", Toast.LENGTH_SHORT).show();
                    return;
                }
                    addToCloud(mGroupId);
                break;
            case R.id.edit_rl_sex:
                try {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(AddContactByHandActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                showSetSexPop();
                break;
        }
    }


    private void addToCloud(String groupId) {
        String contactName = mEtName.getText().toString();
        String contactCompany = mEtCompany.getText().toString();
//        String contactDepartment = mEtDepartment.getText().toString();
        String contactPosition = mEtPosition.getText().toString();
        String contactPhone1 = mEtPhone1.getText().toString();
//        String contactPhone2 = mEtPhone2.getText().toString();
        String contactEmail = mEtEmail.getText().toString();
        String contactAddress = mEtAddress.getText().toString();
        String contactMessage = mEtMessage.getText().toString();
        JSONArray jNameCardList = new JSONArray();
        JSONObject jCloudContact = new JSONObject();
        JSONArray jPhoneNum = new JSONArray();
        jPhoneNum.put(Constants.GENERAL_LABEL_WORK);
        jPhoneNum.put(contactPhone1);
//        jPhoneNum.put(Constants.GENERAL_LABEL_HOME);
//        jPhoneNum.put(contactPhone2);
        try {
            JSONObject jNameCard = new JSONObject();
            if (!StringUtil.isEmpty(contactEmail)) {
                com.lzx.iteam.json.JSONArray email = new com.lzx.iteam.json.JSONArray();
                contactEmail = Base64.encodeToString(contactEmail.getBytes(), Base64.NO_WRAP);
                email.add(contactEmail);
                email.add(Base64.encodeToString(Constants.GENERAL_LABEL_HOME.getBytes(), Base64.NO_WRAP));
                jNameCard.put("demails", email);
            }
            if (
                //(
                    !StringUtil.isEmpty(contactPhone1)
                //  ) || (!StringUtil.isEmpty(contactPhone2))
                    ) {
                com.lzx.iteam.json.JSONArray phone = new com.lzx.iteam.json.JSONArray();
                contactPhone1 = Base64.encodeToString(contactPhone1.getBytes(), Base64.NO_WRAP);
//                contactPhone2 = Base64.encodeToString(contactPhone2.getBytes(), Base64.NO_WRAP);
                phone.add(contactPhone1);
                phone.add(Base64.encodeToString(Constants.GENERAL_LABEL_WORK.getBytes(), Base64.NO_WRAP));
//                phone.add(contactPhone2);
//                phone.add(Base64.encodeToString(Constants.GENERAL_LABEL_HOME.getBytes(), Base64.NO_WRAP));
                jNameCard.put("dphones", phone);
            }
            if (!StringUtil.isEmpty(contactAddress)) {
                com.lzx.iteam.json.JSONArray address = new com.lzx.iteam.json.JSONArray();
                contactAddress = Base64.encodeToString(contactAddress.getBytes(), Base64.NO_WRAP);
                address.add(contactAddress);
                address.add(Base64.encodeToString(Constants.GENERAL_LABEL_WORK.getBytes(), Base64.NO_WRAP));
                jNameCard.put("daddresses", address);
            }

            String userId = "0";
            if (!StringUtil.isEmpty(contactCompany)) {
            jNameCard.put("jobtitle", Base64.encodeToString(
                    contactCompany.getBytes(), Base64.NO_WRAP));}
            if (!StringUtil.isEmpty(contactPosition)) {
            jNameCard.put("organization", Base64.encodeToString(
                    contactPosition.getBytes(), Base64.NO_WRAP));}

//            jNameCard.put("department", Base64.encodeToString(
//                    contactDepartment.getBytes(), Base64.NO_WRAP));
            HashMap<String, String> userIdMap = (HashMap<String, String>) PreferenceUtil.getInstance(AddContactByHandActivity.this).getCloudContact(PreferenceUtil.CLOUD_PHONE_2_USEID);
            if (userIdMap != null) {
                userId = userIdMap.get(PhoneNumberArea.formatPhoneNumDisplay(jPhoneNum.getString(1)));
            }
            jCloudContact.put(AsynHttpClient.KEY_CONTACT_NAME, StringUtil.ensureEmptyStr(contactName));
            jCloudContact.put(AsynHttpClient.KEY_CONTACT_REMARKS, StringUtil.ensureEmptyStr(contactMessage));
            jCloudContact.put(AsynHttpClient.KEY_CONTACT_PHONENUMBER, jPhoneNum);
            jCloudContact.put(AsynHttpClient.KEY_CONTACT_NAMECARD, jNameCard);
            jCloudContact.put(AsynHttpClient.KEY_USER_ID, userId);
            jCloudContact.put(AsynHttpClient.KEY_SEX,mContactSex);

            jNameCardList.put(jCloudContact);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        addContactList(StringUtil.compressByGzip(jNameCardList.toString()), groupId);
//        NameCardUtil.contact2JsonCloudUpload(contactId, jNameCardList, this);

    }

    private void addContactList(String contactListStr, String groupId) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID,
                LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, groupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CONTACTS_LIST, contactListStr));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TYPE, "1"));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TAG_ID, mTagId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CONTACTS_NUM, "1"));
        AddContactListMsg addContactList = new AddContactListMsg(mHandler.obtainMessage(MSG_ADD_CONTACT));
        addContactList.mApi = AsynHttpClient.API_CONTACT_ADDLIST;
        addContactList.mParams = nvps;
        AsynHttpClient.getInstance(this).execCcHttp(addContactList);
    }

    /**
     * 选择性别
     */
    public void showSetSexPop() {
        View mainView = LayoutInflater.from(this).inflate(R.layout.edit_sex_pop_layout, null);
        Button boy = (Button) mainView.findViewById(R.id.edit_sex_boy);
        Button girl = (Button) mainView.findViewById(R.id.edit_sex_girl);
        Button cancel = (Button) mainView.findViewById(R.id.edit_sex_cancle);

        boy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mContactSex = "1";
                mSex.setText("男");
                mSex.setTextColor(getResources().getColor(R.color.black));
                mSetSexPop.dismiss();
            }
        });

        girl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mContactSex = "2";
                mSex.setText("女");
                mSex.setTextColor(getResources().getColor(R.color.black));
                mSetSexPop.dismiss();
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSetSexPop.dismiss();
            }
        });

        mSetSexPop = new PopupWindow(this);
        mSetSexPop.setBackgroundDrawable(new BitmapDrawable());
        mSetSexPop.setFocusable(true);
        mSetSexPop.setTouchable(true);
        mSetSexPop.setOutsideTouchable(true);
        mSetSexPop.setContentView(mainView);
        mSetSexPop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mSetSexPop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mSetSexPop.setAnimationStyle(R.style.bottomStyle);
        mSetSexPop.showAtLocation(mMainView, Gravity.BOTTOM, 0, 0);
        mSetSexPop.update();

    }

}
